package com.example.gulimall.order.config;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.common.vo.order.PayVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "alipay")
public class AlipayTemplate {

    //在支付宝创建的应用的id
    private String app_id = "2021001128637981";

    // 商户私钥，您的PKCS8格式RSA2私钥
    private String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCumnBaZ0IKIo9GGxDbCfX/EChSNb8uTiU8E6LhjJzfnaKBusMZq9mtNOV1z3Y0Gyri+2czsZGDZ5xZ+bBxsNK93tS4ynOUf5SpxBA5hT4deH901Bawjc/swPwU9eSAt6/M80w8iEQsOwGWQw7K0jtva72mA5Fza78MZjrspN+9BP6HjUDiBjej8Ahp13RmrW+rKbI7lBk692pkqYUs2Z9fu4tvCnHopF1DV9bIc2iJdnwbhTE2xBf8HMQAS6c+47oMi+Ft5iFwJKlzIHZJbyTstPwTwI+CyjROTq7QZcF3vX7XI9drO/a/0fUeRZmHsZbsCHuF627POEnjBoPL1gRBAgMBAAECggEATcoEsGI8q+NFzcgVNGE1tdNvA2FqsaijMibVdIN/CKlkU0Pv1CoaKu7cJCav1Psdmk7DZeaAm/i3UebKU3yiB3GVeFbKM6i7hP8S822HhP3AWz56dWJY9nPsWzJKAYbUzgy/NGDJbqNDS7zIhFgxnqxzq9j/HlssnMuXCQNToxQu1ClzEoCGvFYhHsyjunwTCXce1Tuv1BAt3uCBxssijY7C1rA8ZwyOf/EuYjyG9yX6VEt6wCTlzsMAYQIzOjxoph853QGldxMAy1wrastdE3ZTTlrctNryBi/N0YJBTpgy3CIwvwUzMcdl5SQV6H0UfzU4o9cHsS5Sv/cFNMr5oQKBgQDuBQzQFd/8nRCi//HhT/A0b8ehr7Gs66lONIBC8KTv5Q+gT6UKmRWtVKOG9op257qcxi4lgog3wx999YwMFAeTxWs/lblzJ1bXUaR39RLSWelgjxWUxiSD8ey+A5aS2oG28xhHl7rJBt5wdMr66iu8uBC9opO2vYRPQ7jjTHGFHQKBgQC7ywIjtklBa3LJThHzwHvqgLeDIzF7KhzEFK4IComUjmMtjT8LQYVGT+N6swEmWJ7NnsM68qVIKH+6MlsgPXffw14Bo3efh9/4njAg2S9PaOiNQYXvbdQUenUW26TGM2BY1f10orixpo0mLSKiksPU3qSJkg0cG2ZnHI+aQbOGdQKBgQDP60drCoDUadvbl5sSyEK7e522xwR9WotWDpSwZQifqsgAsTIp1NpTxGjo/7qq7fhc9N3g1Grr0x5SaMoCzwhjdIQgUklip02738y9IS9k4zfzqmoewQuq2w2EWxwQgqHnT+m4uHlpG//52nxpvV+hhmTRUxCYBGts1mrO27sanQKBgQCGjkk0KXKHy2Nt1eCLFMo1FpFnBxp3M49095RS8qntpbBufRxFBmdmH+vQiN40CZ+PmUgtvpqq/0m1sksU6LYxwJxk9CnMRuE2FLJLdxKtBXBLdj1vdvRU0AGBpVOFKF7KiFmY7tcDg2Dzj7eXYS2sIvMmF14JW6CeFRrX3mex2QKBgA16YFcmitjm3E7X5k7vz5NtPvDE/ntmoxUe1u2/HheDVdWb0NPFIAzpGZllndIKv4VES89z1BP1vB8vLxAmm6EfE+1UmUMvA38gAfs5nSbb8H4C5+QRu9Uzhy26gj7KXDijpk2UBkUFQPLi3oyljfk2O3ZsozgfbN14n1jaU8jv";
    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    private String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAupskEuo/mUdum+DvfrKdxz3vNwMtH2Y9KOthYP7kp8bIwMG5sRSl3NRTgBcToTIhOl1S43R7y1TZCGRYcgiZgiPTt9mZOMXOAbSA4AZ1xFAzrrqtZrq8jOEFdOJ5vvnTYgnUuOMRW9YVDtt2ckWAqzEpGb5xlq41iN+iJpAQeQ2Se7xeth5IN+csFbi4zu1dvU7Mma/FsOVsLCM3gA6/ibCbN/+K7JPK5B5pfryZHs0WoEPwQXagJciaxviAYZ1DRw+v44j/GsynRAQOzZpwkqTp7rfR85s+nM21dBsfNR2hPaxU1Ky1fJvHB27pubLam9Jf8Mel9fLekhLrmHERDQIDAQAB";
    // 服务器[异步通知]页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    // 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息
    private String notify_url;

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    //同步通知，支付成功，一般跳转到成功页
    private String return_url;

    // 签名方式
    private String sign_type = "RSA2";

    // 字符编码格式
    private String charset = "utf-8";

    private String timeout;

    // 支付宝网关； https://openapi.alipaydev.com/gateway.do
    private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    public String pay(PayVo vo) throws AlipayApiException {

        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayTemplate.gatewayUrl, AlipayTemplate.app_id, AlipayTemplate.merchant_private_key, "json", AlipayTemplate.charset, AlipayTemplate.alipay_public_key, AlipayTemplate.sign_type);
        //1、根据支付宝的配置生成一个支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl,
                app_id, merchant_private_key, "json",
                charset, alipay_public_key, sign_type);

        //2、创建一个支付请求 //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = vo.getOut_trade_no();
        //付款金额，必填
        String total_amount = vo.getTotal_amount();
        //订单名称，必填
        String subject = vo.getSubject();
        //商品描述，可空
        String body = vo.getBody();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                // 设置订单相对超时时间
                + "\"timeout_express\":\"3m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //会收到支付宝的响应，响应的是一个页面，只要浏览器显示这个页面，就会自动来到支付宝的收银台页面
        log.info("支付宝的响应：{}", result);

        return result;
    }


    public void close(String out_trade_no) {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(this.gatewayUrl, this.app_id,
                this.merchant_private_key, "json", this.charset, this.alipay_public_key, this.sign_type);

        //设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"}");

        try {
            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
            String response = String.valueOf(jsonObject.get("alipay_trade_close_response"));
            JSONObject subResp = JSONObject.parseObject(response, JSONObject.class);

            Integer code = Integer.parseInt(String.valueOf(subResp.get("code")));
            if (code == 10000) {
                log.info("订单过期，手动触发订单关闭成功: {}", subResp);
                return;
            }
            log.info("订单过期，手动触发订单关闭失败：{}", result);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("订单过期，关闭支付宝交易发生异常：", ex);
        }
    }
}
